import { useMemo, useState } from 'react';
import Taro, { useDidShow, useLoad, useShareAppMessage } from '@tarojs/taro';
import { View, Text, Image, Button } from '@tarojs/components';
import { AtList, AtProgress, AtIcon, AtModal, AtModalHeader, AtModalContent, AtModalAction } from 'taro-ui';
import ListItem from '@/components/ListItem';
import styles from './index.module.scss'
import { WxMyPageVO } from '@/business/services/user/userInfo/types';
import { initUser } from '@/business/services/im';
import { formatHttp2Https } from '@/utils/format';
import { useUserStore } from '@/business/store/user/login';
import { getMyPageUserInfo, getUserVipInfo } from '@/business/services/user/userInfo';
import { wxLogout, wxUserCancel } from '@/business/services/user/login/login';
import { destroySdk } from '@/utils/im';
import './index.scss'

const ProfilePage: React.FC = () => {
  const useUser = useUserStore();
  const [vipTime, setVipTime] = useState('')
  const [userInfo, setUserInfo] = useState<WxMyPageVO>(useUser.userInfo)

  useLoad(() => {
    getMyVipInfo()

  })

  const [isOpened, setIsOpened] = useState(false)

  const getMyVipInfo = async () => {
    const res = await getUserVipInfo()
    setVipTime(res.data?.endTime || '')
    if (res.success) {
      useUser.setUserVip(res.data)
    }
  }
  const updateUserInfo = async () => {
    const res = await getMyPageUserInfo()
    useUser.setUserInfo(res.data)
    setUserInfo(res.data)
  }

  useShareAppMessage((res) => {
    console.log(userInfo, 'userInfo')
    return {
      title: '好友邀请你一起加入豹友群！找资源？进豹友群！',
      path: `/pages/index/index?inviteCellphone=${userInfo.extraPhones ? userInfo.extraPhones[0] : ''}`,
      imageUrl: 'https://baoyouqun.cn/files/2025/10/18/31611484-f865-4395-a4e0-90a123cfb3df.png'
    }
  })

  useDidShow(() => {
    getMyVipInfo()
    updateUserInfo()
  })

  const stats = useMemo(
    () => [
      { label: '我的发布', value: (userInfo.ownedResourcesNum || 0) + (userInfo.neededResourcesNum || 0), onClick: () => handleMyPlublish() },
      { label: '我的好友', value: userInfo.myFriendNum, onClick: () => handleMyFriends() },
      { label: '我的收藏', value: userInfo.myCollectionsNum, onClick: () => handleMyFavorites() },
      { label: '我的积分', value: userInfo.pointsNum, onClick: () => handleMyPoints() },
    ],
    [],
  );

  // 收货地址
  const handleShippingAddress = () => {
    Taro.navigateTo({
      url: `/subPackages/addUserAddress/index`,
    });
  };

  // 城市合伙人
  const handleCityPartnerApplication = () => {
    Taro.navigateTo({
      url: `/subPackages/cityPartnerApplication/index`,
    });
  }

  // 我的发布
  const handleMyPlublish = () => {
    Taro.navigateTo({
      url: `/subPackages/myPublish/index`,
    });
  }

  // 我的好友
  const handleMyFriends = () => {
    Taro.reLaunch({
      url: `/pages/contact/index?tabIndex=0`,
    });
  }

  // 我的收藏
  const handleMyFavorites = () => {
    Taro.navigateTo({
      url: `/subPackages/myCollection/index`,
    });
  }

  // 我的积分
  const handleMyPoints = () => {
    Taro.navigateTo({
      url: `/pages/credits/index`,
    });
  }

  // 举报记录
  const handleReportRecord = () => {
    Taro.navigateTo({
      url: `/subPackages/reportRecord/index`,
    });
  }



  const handleLogout = async () => {
    await wxLogout({})
    useUser.logout()
    Taro.clearStorageSync()
    destroySdk()
    Taro.reLaunch({
      url: `/pages/index/index`,
    });
  }

  const handleCancelModal = async () => {
    setIsOpened(true)
  }

  const handleCancel = async () => {
    await wxUserCancel({})
    Taro.clearStorageSync()
    destroySdk()
    Taro.reLaunch({
      url: `/pages/login/index`,
    });
  }

  // 权益中心
  const handleEquity = (e: any) => {
    e.stopPropagation();
    Taro.navigateTo({
      url: `/subPackages/equity/index`,
    });
  };

  const goPersonPage = () => {
    Taro.navigateTo({
      url: `/subPackages/person/index?redirect=user`,
    })
  }

  // 开具发票
  const handleInvoice = () => {
    Taro.navigateTo({
      url: `/subPackages/invoice/index`,
    })
  }

  // 修改联系方式
  const handleContact = () => {
    Taro.navigateTo({
      url: `/subPackages/editPhone/index`,
    })
  }

  // 专属客服
  const handleService = () => {
    Taro.navigateTo({
      url: '/pages/service/index'
    })
    // Taro.openCustomerServiceChat({
    //   corpId: '',
    //   extInfo: {
    //     url: ''
    //   },
    //   success: () => {
    //     console.log('打开客服成功');
    //   },
    //   fail: (err) => {
    //     console.log('打开客服失败', err);
    //   }
    // });
  };

  return (
    <View className={styles.page}>
      {/* 顶部个人信息卡 */}
      <View className={styles.headerCard} onClick={goPersonPage}>
        <View>
          <View className={styles.avatarWrap}>
            {/* 用内置 avatar 图标；如有头像 URL 可换成 <Image /> */}
            <View className={styles.avatar}>
              <Image src={formatHttp2Https(userInfo?.headImg) || 'https://baoyouqun.cn/files/static/images/person.png'} mode='aspectFill' />
            </View>
          </View>

          <View className={styles.userInfo}>
            <Text className={styles.name}>{userInfo.name ?? ''}</Text>
            <Text className={styles.phone}>{userInfo.cellphone ?? ''}</Text>

            <View className={styles.metaRow}>
              <Text className={styles.metaText}>基本资料已完善啦</Text>
              <Text
                className={styles.link}
              >
                去优化资料
              </Text>
            </View>
            <AtProgress percent={userInfo.dataCompletion ?? 0} color='#0079FE' />
          </View>
        </View>
        <View className={styles.chevronRight}>
          <AtIcon value='chevron-right' size='20' color='#86909C'></AtIcon>
        </View>
      </View>

      {/* 统计区块 */}
      <View className={styles.statsCard}>
        <View className='at-row'>
          {stats.map((s) => (
            <View className='at-col' key={s.label} style={{ flex: 1, textAlign: 'center' }} onClick={s.onClick}>
              <View className={styles.statItem}>
                <Text className={styles.statValue}>{s.value}</Text>
                <Text className={styles.statLabel}>{s.label}</Text>
              </View>
            </View>
          ))}
        </View>
      </View>

      {/* VIP 横幅 */}
      {
        useUser?.vipInfo?.vipLevelId === '001' ? <View className={styles.vip}>
          <View className={styles.vipedBanner}>
            <View className={styles.vipLeft}>
              <Text className={styles.vipedTitle}>您已开通VIP特权</Text>
              <Text className={styles.vipedSub}>会员有效期至 {vipTime}</Text>
            </View>
            <View className={styles.vipedRight} onClick={handleEquity}>
              <Text className={styles.vipedRightText}>去续费</Text>
            </View>
          </View>
        </View> : <View className={styles.vip}>
          <View className={styles.vipBanner}>
            <View className={styles.vipLeft}>
              <Text className={styles.vipTitle}>超级VIP特权</Text>
              <Text className={styles.vipSub}>更多会员特权尽情享受</Text>
            </View>
            <View className={styles.vipRight} onClick={handleEquity}>
              <Text className={styles.vipRightText}>了解更多</Text>
            </View>
          </View>
        </View>
      }

      {/* 功能列表 */}
      <View className={styles.listWrap}>
        <AtList hasBorder={false}>
          <ListItem title='收货地址' rightText={userInfo.receivedInfo || ''} onRightClick={handleShippingAddress} />
          <ListItem title='邀请好友' rightText={userInfo.inviteFriendsTips || ''}>
            <Button className={styles.shareBtn} openType="share">分享给好友</Button>
          </ListItem>
          <ListItem title='开具发票' onRightClick={handleInvoice} />
          <View className={styles.gap}></View>
          <ListItem title='修改联系方式' rightText='修改手机号隐私' onRightClick={handleContact} />
          <View className={styles.gap}></View>
          <ListItem title='城市合伙人' rightText='立即申请加入' onRightClick={handleCityPartnerApplication} />
          <ListItem title='专属客服'>
            <Button className={styles.shareBtn} openType="contact" sendMessageTitle='豹友群客服'>专属客服</Button>
          </ListItem>
          <ListItem title='举报记录' onRightClick={handleReportRecord} />
          <ListItem title='注销账号' onRightClick={handleCancelModal} />
          <ListItem title='退出登录' onRightClick={handleLogout} />
          {/* <ListItem title='公司理念' onRightClick={handleShippingAddressClick} />
          <ListItem title='版本信息' rightText='v1.0' onRightClick={handleShippingAddressClick} />
          <ListItem title='注销账号' onRightClick={handleShippingAddressClick} /> */}
        </AtList>
      </View>
      <AtModal isOpened={isOpened} className='cancel-account-modal'>
        <AtModalHeader>注销账号</AtModalHeader>
        <AtModalContent>
          是否注销此账号
        </AtModalContent>
        <AtModalAction> <Button onClick={() => {
          setIsOpened(false)
        }}>取消</Button> <Button onClick={handleCancel}>确定</Button> </AtModalAction>
      </AtModal>
    </View>
  );
};

export default ProfilePage;
